const METHOD = ['get', 'post']
const BASE_URL = '/v1'

let total = 60
let users = []
let Random = Mock.Random
for (let i = 0; i < total; i++) {
  users.push(
    Mock.mock({
      id: i + 1,
      username: Random.name(),
      'age|18-50': 1,
      email: Random.email()
    })
  )
}

Mock.mock(BASE_URL + '/user/queryUsers', METHOD[1], queryUsers)
Mock.mock(BASE_URL + '/user/deleteUser', METHOD[0], deleteUser)
Mock.mock(BASE_URL + '/user/updateUser', METHOD[1], updateUser)
Mock.mock(BASE_URL + '/user/insertUser', METHOD[1], insertUser)

/** 查询用户记录 */
function queryUsers(options) {
  const params = JSON.parse(options.body)
  let result = []
  if (params.pageSize || params.currentPage) {
    result = users.slice(
      (params.currentPage - 1) * params.pageSize,
      params.currentPage * params.pageSize
    )
  } else {
    result = users.slice(0, 10)
  }

  return {
    result,
    total: users.length,
    success: true
  }
}

/** 删除用户记录 */
function deleteUser(options) {
  printInfo(JSON.parse(options.body))
  const { id } = JSON.parse(options.body)
  users.splice(id - 1, 1)

  return {
    result: 'delete success',
    success: true
  }
}

/** 修改用户记录 */
function updateUser(options) {
  printInfo(JSON.parse(options.body))
  const params = JSON.parse(options.body)
  users.find((item) => {
    if (item.id === params.id) {
      item = params
    }
  })

  return {
    result: 'update success',
    success: true
  }
}

/** 新增用户记录 */
function insertUser(options) {
  printInfo(JSON.parse(options.body))
  const params = JSON.parse(options.body)
  users.push({ id: users.length + 1, ...params })

  return {
    result: 'insert success',
    success: true
  }
}
